package com.hnevc.registerandlogin;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {
    EditText mEtUserName;//用户名编辑框
    EditText mEtPassword;//密码编辑框
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mEtUserName = (EditText) findViewById(R.id.id_et_username);
        mEtPassword = (EditText) findViewById(R.id.id_et_password);
    }
    //登录
    public void login(View view){
        //TODO 从内部文件中读取用户名和密码信息进行登录权限的判断
        try {
            //获取保存在内部文件中的用户名和密码
            String[] usernamepassword = getUserNamePassword();
            //获取用户名和密码
            String username = mEtUserName.getText().toString();
            String password = mEtPassword.getText().toString();
            //验证用户名和密码是否与保存的用户名和密码相同
            if(username.equals(usernamepassword[0])
                    && password.equals(usernamepassword[1])){
                Toast.makeText(this, "用户名密码正确", Toast.LENGTH_SHORT).show();
                
            }else{
                Toast.makeText(this, "用户名或者密码错误！", Toast.LENGTH_SHORT).show();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String[] getUserNamePassword() throws IOException {
        FileInputStream fis = openFileInput("data.txt");
        byte[] bytes = new byte[fis.available()];
        fis.read(bytes);
        fis.close();
        String s = new String(bytes);
        String[] strings = s.split("-");
        return strings;
    }

    //注册
    public  void regist(View view){
        Intent intent = new Intent();
        intent.setClass(this,RegistActivity.class);
        startActivityForResult(intent,1);//设置回传调用新的Activity
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode==1 && resultCode==1) {
            //获取回传的username数据
            String username = data.getStringExtra("username");
            mEtUserName.setText(username);
        }
    }

}
